package Exercise;

import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;
    public TestHeap() {
        this.elem=new int[10];
    }

    //初始化
    public void init(int[] array) {
        for(int i=0;i<array.length;i++) {
            elem[i]=array[i];
            usedSize++;
        }
    }

    public boolean isFull() {
        return elem.length==usedSize;
    }

    //将已有数据初始化为一个大根堆
    public void createBigHeap() {
        int child=usedSize-1;
        for(int parent=(child-1)/2;parent >=0;parent--) {
            siftDown(parent,usedSize);
        }
    }

    public void siftDown(int parent,int end) {
        int child=2*parent+1;
        while(child<end) {  //一直遍历到child超过usedSize
            if(child+1<end && elem[child+1]>elem[child]) {
                child++;//让child指向更大的那个子节点
            }
            if(elem[child]>elem[parent]) {
                swap(child,parent);
                parent=child;
                child=2*parent+1;
            }else {
                break;
            }
        }
    }
    public void swap(int i,int j) {
        int temp=elem[i];
        elem[i]=elem[j];
        elem[j]=temp;
    }

    public void offer(int val) {
        if(isFull()) {
            elem=Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize++]=val;
        siftUp(usedSize-1);
    }
    public void siftUp(int child) {
        int parent=(child-1)/2;
        while(parent>=0) {
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public int poll() {
        if(isEmpty()) {
            return -1;
        }
        int old=elem[0];
        swap(0,usedSize-1);
        usedSize--;
        siftDown(0,usedSize);
        return old;
    }
    public boolean isEmpty() {
        return usedSize==0;
    }

}
